package com.ruoyi.drone.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.StringUtils;

/**
 * 照片上传工具类
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
public class PhotoUploadUtils 
{
    /** 允许的图片格式 */
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList("jpg", "jpeg", "png", "gif", "webp");
    
    /** 最大文件大小（10MB） */
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;
    
    /** 照片类型路径映射 */
    private static final String IDCARD_FRONT_PATH = "/upload/idcard/front/";
    private static final String IDCARD_BACK_PATH = "/upload/idcard/back/";
    private static final String EXPLORATION_PATH = "/upload/exploration/";
    private static final String QUALIFICATION_PATH = "/upload/qualification/";
    private static final String CERT_PATH = "/upload/cert/";
    private static final String SKILL_PATH = "/upload/skill/";
    private static final String LICENSE_PATH = "/upload/license/";
    private static final String TASK_IMAGE_PATH = "/upload/task_image/";

    /**
     * 上传照片
     * 
     * @param file 上传的文件
     * @param photoType 照片类型
     * @param basePath 基础路径
     * @return 照片URL
     */
    public static String uploadPhoto(MultipartFile file, String photoType, String basePath) throws IOException 
    {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        String fileExtension = getFileExtension(originalFilename);
        if (!ALLOWED_IMAGE_TYPES.contains(fileExtension.toLowerCase())) {
            throw new IllegalArgumentException("不支持的文件格式，只支持：" + String.join(", ", ALLOWED_IMAGE_TYPES));
        }

        // 验证文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("文件大小不能超过10MB");
        }

        // 生成唯一文件名
        String fileName = generateFileName(photoType, fileExtension);
        
        // 确定上传路径
        String uploadPath = getUploadPath(photoType, basePath);
        
        // 创建目录
        Path directory = Paths.get(uploadPath);
        if (!Files.exists(directory)) {
            Files.createDirectories(directory);
            System.out.println("创建目录: " + directory.toAbsolutePath());
        }

        // 保存文件
        Path filePath = directory.resolve(fileName);
        Files.copy(file.getInputStream(), filePath);
        
        System.out.println("文件保存到: " + filePath.toAbsolutePath());
        System.out.println("文件大小: " + file.getSize() + " bytes");

        // 返回访问URL
        String photoUrl = getPhotoUrl(photoType, fileName);
        System.out.println("返回URL: " + photoUrl);
        return photoUrl;
    }

    /**
     * 删除照片
     * 
     * @param photoUrl 照片URL
     * @param basePath 基础路径
     * @return 是否删除成功
     */
    public static boolean deletePhoto(String photoUrl, String basePath) 
    {
        if (StringUtils.isEmpty(photoUrl)) {
            return false;
        }

        try {
            // 从URL中提取文件路径
            String fileName = extractFileNameFromUrl(photoUrl);
            if (StringUtils.isEmpty(fileName)) {
                return false;
            }

            // 确定文件路径
            String photoType = getPhotoTypeFromUrl(photoUrl);
            String uploadPath = getUploadPath(photoType, basePath);
            Path filePath = Paths.get(uploadPath, fileName);

            // 删除文件
            if (Files.exists(filePath)) {
                Files.delete(filePath);
                return true;
            }
        } catch (Exception e) {
            // 记录日志
            System.err.println("删除照片失败：" + e.getMessage());
        }

        return false;
    }

    /**
     * 验证照片URL是否有效
     * 
     * @param photoUrl 照片URL
     * @return 是否有效
     */
    public static boolean isValidPhotoUrl(String photoUrl) 
    {
        if (StringUtils.isEmpty(photoUrl)) {
            return false;
        }

        // 检查URL格式
        if (!photoUrl.startsWith("http://") && !photoUrl.startsWith("https://")) {
            return false;
        }

        // 检查文件扩展名
        String fileExtension = getFileExtension(photoUrl);
        return ALLOWED_IMAGE_TYPES.contains(fileExtension.toLowerCase());
    }

    /**
     * 获取文件扩展名
     */
    private static String getFileExtension(String filename) 
    {
        if (StringUtils.isEmpty(filename)) {
            return "";
        }
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1);
    }

    /**
     * 生成唯一文件名
     */
    private static String generateFileName(String photoType, String fileExtension) 
    {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return photoType + "_" + uuid + "." + fileExtension;
    }

    /**
     * 获取上传路径
     */
    private static String getUploadPath(String photoType, String basePath) 
    {
        String relativePath;
        switch (photoType) {
            case "idcard_front":
                relativePath = IDCARD_FRONT_PATH;
                break;
            case "idcard_back":
                relativePath = IDCARD_BACK_PATH;
                break;
            case "exploration":
                relativePath = EXPLORATION_PATH;
                break;
            case "qualification":
                relativePath = QUALIFICATION_PATH;
                break;
            case "certificate":
                relativePath = CERT_PATH;
                break;
            case "skill_proof":
                relativePath = SKILL_PATH;
                break;
            case "license":
                relativePath = LICENSE_PATH;
                break;
            case "task_image":
                relativePath = TASK_IMAGE_PATH;
                break;
            default:
                relativePath = "/upload/other/";
        }
        return basePath + relativePath;
    }

    /**
     * 获取照片访问URL
     */
    private static String getPhotoUrl(String photoType, String fileName) 
    {
        String relativePath;
        switch (photoType) {
            case "idcard_front":
                relativePath = IDCARD_FRONT_PATH;
                break;
            case "idcard_back":
                relativePath = IDCARD_BACK_PATH;
                break;
            case "exploration":
                relativePath = EXPLORATION_PATH;
                break;
            case "qualification":
                relativePath = QUALIFICATION_PATH;
                break;
            case "certificate":
                relativePath = CERT_PATH;
                break;
            case "skill_proof":
                relativePath = SKILL_PATH;
                break;
            case "license":
                relativePath = LICENSE_PATH;
                break;
            case "task_image":
                relativePath = TASK_IMAGE_PATH;
                break;
            default:
                relativePath = "/upload/other/";
        }
        // 返回正确的访问路径，包含 /profile 前缀
        return "/profile" + relativePath + fileName;
    }

    /**
     * 从URL中提取文件名
     */
    private static String extractFileNameFromUrl(String photoUrl) 
    {
        if (StringUtils.isEmpty(photoUrl)) {
            return "";
        }
        int lastSlashIndex = photoUrl.lastIndexOf('/');
        if (lastSlashIndex == -1 || lastSlashIndex == photoUrl.length() - 1) {
            return "";
        }
        return photoUrl.substring(lastSlashIndex + 1);
    }

    /**
     * 从URL中获取照片类型
     */
    private static String getPhotoTypeFromUrl(String photoUrl) 
    {
        if (StringUtils.isEmpty(photoUrl)) {
            return "";
        }
        
        if (photoUrl.contains("/idcard/front/")) {
            return "idcard_front";
        } else if (photoUrl.contains("/idcard/back/")) {
            return "idcard_back";
        } else if (photoUrl.contains("/exploration/")) {
            return "exploration";
        } else if (photoUrl.contains("/qualification/")) {
            return "qualification";
        } else if (photoUrl.contains("/cert/")) {
            return "certificate";
        } else if (photoUrl.contains("/skill/")) {
            return "skill_proof";
        } else if (photoUrl.contains("/license/")) {
            return "license";
        } else if (photoUrl.contains("/task_image/")) {
            return "task_image";
        }
        
        return "other";
    }
}
